# -*- coding: utf-8 -*-

import os
from django.http import Http404
from django.http import FileResponse

import logging
logger = logging.getLogger('bt_server')

from base.settings import TORRENT_FOLDER_ROOT, FOLDER_CATEGORY_PATH_DICT
from common.base_resful_view import BaseResfulView


class TorrentFileDownload(BaseResfulView):

    def get(self, request, category, file_name):
        """ 
        torrent 文件下载(非bt)
        """
        logger.info('category:{} file_name:{}'.format(category, file_name))
        file_path = os.path.join(TORRENT_FOLDER_ROOT, category, file_name)
        if not os.path.isfile(file_path):
            raise Http404('没有该文件')
        f = open(file_path, 'rb')
        response = FileResponse(f)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
        return response


class ResourceDownload(BaseResfulView):

    def get(self, request, category, file_name):
        """ 
            资源下载(非bt)
        """
        logger.info('category:{} file_name:{}'.format(category, file_name))
        folder_path = FOLDER_CATEGORY_PATH_DICT.get(category)
        if not folder_path:
            raise Http404('错误的分类')

        file_path = os.path.join(folder_path, file_name)
        if not os.path.isfile(file_path):
            raise Http404('没有该文件')
        f = open(file_path, 'rb')
        response = FileResponse(f)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
        return response